package net.pws.oos.web;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.pws.common.jackson.JsonUtils;
import net.pws.common.persistence.EntityManager;
import net.pws.common.persistence.IPage;
import net.pws.common.security.SecurityContext;
import net.pws.common.util.StringUtils;
import net.pws.oos.biz.model.Area;
import net.pws.oos.biz.model.Attachment;
import net.pws.oos.biz.model.IndicatorValue;
import net.pws.oos.biz.model.Station;
import net.pws.oos.biz.model.StationRecord;
import net.pws.oos.biz.model.User;
import net.pws.oos.biz.query.AttachmentFinder;
import net.pws.oos.biz.query.IndicatorFinder;
import net.pws.oos.biz.query.StationFinder;
import net.pws.oos.biz.query.SystemManageFinder;
import net.pws.oos.biz.query.parameter.StationQueryParameter;
import net.pws.oos.biz.service.StationService;
import net.pws.oos.security.SecurityUtils;
import net.pws.oos.web.dto.AttachmentDto;
import net.pws.oos.web.dto.PhotoMarkerDto;
import net.pws.oos.web.dto.StationDto;
import net.pws.oos.web.dto.StationRecordDto;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/biz/station")
@SuppressWarnings("rawtypes")
public class StationAction implements ServletContextAware {
    
    private final transient Log logger = LogFactory.getLog(StationAction.class);
    
    @Autowired
    protected EntityManager entityManager;
    
    @Autowired
    private StationService stationService;
    
    @Autowired
    private StationFinder stationFinder;
    
    @Autowired
    private IndicatorFinder indicatorFinder;
    
    @Autowired
    private AttachmentFinder attachmentFinder;
    
    @Autowired
    private SystemManageFinder systemManageFinder;
    
    @Autowired
    @Qualifier("attachmentPath")
    private String attachmentPath;
    
    private ServletContext context;
    
    public void setServletContext(ServletContext context) {
        this.context = context;
    }
    
    @RequestMapping(value = "/importBrandSort.do", method = RequestMethod.POST)  
    public String importBrandSort(@RequestParam("filename") MultipartFile file,HttpServletRequest request,HttpServletResponse response,ModelMap map) throws Exception {  
        if (file == null)  
            return null;  
        logger.info(file.getOriginalFilename());  
  
        String name = file.getOriginalFilename();// 获取上传文件名,包括路径  
        long size = file.getSize();  
        if ((name == null || name.equals("")) && size == 0)  
            return null;  
        InputStream in = file.getInputStream();
        StringBuffer errorMsg = new StringBuffer();  
        
        String configFilePath = request.getRealPath("/biz/station/import/excel_column.txt");
        logger.debug(String.format("配置文件路径：%s", configFilePath));
        stationService.importStation(in, configFilePath, errorMsg, SecurityUtils.currentUserId());
        if(errorMsg.length() == 0){
        	errorMsg.append("导入成功！");
        }else{
        	logger.error(errorMsg.toString());  
        }
        
        map.put("msg", errorMsg.toString());
        return "station/import/excel";
    }  

    /**
     * 查询页面
     * 
     * @return
     */
    @RequestMapping("/list.do")
    public String listPage(StationQueryParameter parameter, ModelMap map) {
        String areaId = "";
        String areaName = "";
        if (StringUtils.isNotBlank(parameter.getAreaId())) {
        	Area area = entityManager.find(Area.class,
                                                 parameter.getAreaId());
            if (area != null) {
                areaId = area.getId();
                areaName = area.getName();
            }
        }
        map.put("areaId", areaId);
        map.put("areaName", areaName);
        
        String countyId = "";
        String countyName = "";
        if (StringUtils.isNotBlank(parameter.getCountyId())) {
        	Area county = entityManager.find(Area.class,
        			parameter.getCountyId());
        	if (county != null) {
        		countyId = county.getId();
        		countyName = county.getName();
        	}
        }
        map.put("countyId", countyId);
        map.put("countyName", countyName);
        
        String constructionModelId = "";
        String constructionModelName = "";
        if (StringUtils.isNotBlank(parameter.getConstructionModelId())) {
        	IndicatorValue constructionModel = entityManager.find(IndicatorValue.class,
        			parameter.getConstructionModelId());
        	if (constructionModel != null) {
        		constructionModelId = constructionModel.getId();
        		constructionModelName = constructionModel.getName();
        	}
        }
        map.put("constructionModelId", constructionModelId);
        map.put("constructionModelName", constructionModelName);
        
        List<Area> areas = entityManager.findList("select new Area(id,name) from Area where parent is null and deleted = 0", new Object[0]);
        map.put("areas", areas);
        if(StringUtils.isNotBlank((String) map.get("areaId"))){
        	List<Area> countys = entityManager.findList("select new Area(id,name) from Area where parent.id = ? and deleted = 0", new Object[]{ map.get("areaId")});
        	map.put("countys", countys);
        }else{
    		map.put("countys", Collections.EMPTY_LIST);
        }
        List<IndicatorValue> constructionModels = indicatorFinder.getIndicatorValueListByIndicatorProp("constructionModel");
		map.put("constructionModels", constructionModels);
        
        return "station/query";
    }
    
    @RequestMapping("/list.json")
    @ResponseBody
    public Object getStationList(StationQueryParameter param) {
        param = initParametersByRole(param);
        
        return listStations(param);
    }
    
    private StationQueryParameter initParametersByRole(StationQueryParameter param) {
        if (param == null) {
            param = new StationQueryParameter();
        }
        
        return param;
    }
    
    private Object listStations(StationQueryParameter param) {
        try {
        	IPage<Map> stations = stationFinder.getStationList(param,
                                                     param.getStart(),
                                                     param.getLimit());
        	
            return JsonUtils.succeedMap(stations);
        }
        catch (Exception e) {
            logger.error(e, e);
            return JsonUtils.failedMap(e.getMessage());
        }
    }
    
    @RequestMapping("/edit.do")
    public String editPage(String id, ModelMap map) {
        if (StringUtils.isEmpty(id)) {
            return "station/new";
        }

        Station station = stationFinder.getStationMap(id);
        map.put("data", StationDto.from(station));
        
        map.put("stationTypes", indicatorFinder.getIndicatorValueListByIndicatorProp("stationType"));
        map.put("sitePropertiess", indicatorFinder.getIndicatorValueListByIndicatorProp("siteProperties"));
        map.put("propertyOwnerships", indicatorFinder.getIndicatorValueListByIndicatorProp("propertyOwnership"));
        map.put("areaTypes", indicatorFinder.getIndicatorValueListByIndicatorProp("areaType"));
        map.put("constructionModels", indicatorFinder.getIndicatorValueListByIndicatorProp("constructionModel"));
        map.put("siteValids", indicatorFinder.getIndicatorValueListByIndicatorProp("siteValid"));
        
        return "station/edit";
    }
    
    @RequestMapping("/detail.do")
    public String detailPage(String id, ModelMap map) {
        map.put("id", id);
        return "station/detail";
    }
    
    @RequestMapping("/detail.json")
    @ResponseBody
    public Object getStationDetail(String id) {
        if (StringUtils.isEmpty(id)) {
            return JsonUtils.failedMap("错误的参数！");
        }
        
        Station station = stationFinder.getStationMap(id);
        if (station == null) {
            return JsonUtils.failedMap("您查找的任务不存在！");
        }
        
        return JsonUtils.succeedMap(StationDto.from(station));
    }
    
    @RequestMapping("/save.json")
    @ResponseBody
    public Object saveStation(StationDto dto) {
        try {
            Station station = null;
            if (StringUtils.isNotEmpty(dto.getId())) {
                station = stationFinder.getStationMap(dto.getId());
            }
            if (station == null) {
                station = new Station();
            }
            
            station = StationDto.to(station, dto, entityManager);
            if (station.getCreateDateTime() == null) {
                station.setCreateDateTime(new Date());
            }
            if (station.getCreator() == null) {
                station.setCreator(entityManager.find(User.class,
                                                   SecurityUtils.currentUserId()));
            }
            if (station.getDeleted() == null) {
            	station.setDeleted(false);
            }
            
            stationService.saveStation(station);
            
            if(station.getStationRecord() == null){
            	StationRecord stationRecordRecod = new StationRecord(station);
                entityManager.persist(stationRecordRecod);
				station.setStationRecord(stationRecordRecod);
            }
            
            return getStationDetail(station.getId());
        }
        catch (Exception e) {
            logger.error(e, e);
            return JsonUtils.failedMap(e.getMessage());
        }
    }
    
    @RequestMapping("/delete.json")
    @ResponseBody
    public Object deleteStation(String id) {
        Station station = stationFinder.getStationMap(id);
        if (station == null) {
            return JsonUtils.succeedMap(id);
        }
        
        if ((station.getCreator() == null) || !station.getCreator()
                                                .getId()
                                                .equals(SecurityContext.getContext()
                                                                       .getId())) {
            return JsonUtils.failedMap("您不是该站点的创建人员，无权限删除该任务！");
        }
        
        try {
        	station.setDeleted(true);
            entityManager.save(station);
            return JsonUtils.succeedMap(id);
        }
        catch (Exception e) {
            logger.error(e, e);
            return JsonUtils.failedMap(e.getMessage());
        }
    }
    
    @RequestMapping("/attachment/list.json")
    @ResponseBody
    public Object getAttachmentList(String resourceId) {
        if (StringUtils.isBlank(resourceId)) {
            return JsonUtils.failedMap("未指定任务！");
        }
        
        List<Attachment> list = attachmentFinder.getPhotos(resourceId);
        List<AttachmentDto> dtos = new ArrayList<AttachmentDto>();
        for (Attachment att : list) {
            dtos.add(AttachmentDto.from(att));
        }
        return JsonUtils.succeedMap(dtos);
    }
    
    /**
     * 修改attachment描述信息
     * 
     * @return
     */
    @RequestMapping("/attachment/updateDescription.json")
    @ResponseBody
    public Object viewPhoto(AttachmentDto attachmentDto) {
    	if (StringUtils.isEmpty(attachmentDto.getId())) {
            return JsonUtils.failedMap("错误的参数！");
        }
        try {
        	Attachment photo = entityManager.find(Attachment.class, attachmentDto.getId());
        	photo.setDescription(attachmentDto.getDescription());
        	entityManager.persist(photo);
            return JsonUtils.succeedMap(photo.getId());
        }
        catch (Exception e) {
            logger.error(e, e);
            return JsonUtils.failedMap(e.getMessage());
        }
    }
    
    /**
     * 得到文件系统中附件根目录的绝对路径
     * 
     * @return
     */
    private String getAttachmentRoot() {
        if (StringUtils.isBlank(attachmentPath)) {
            attachmentPath = context.getRealPath(Attachment.ATTACHMENT_ROOT);
        }
        return attachmentPath;
    }
    
    /**
     * 任务查询页面
     * 
     * @return
     */
    @RequestMapping("/photo.do")
    public String viewPhoto(String id, ModelMap map) {
        Attachment photo = entityManager.find(Attachment.class, id);
        map.put("description", photo.getDescription());
        map.put("path", photo.getOrgiUri());
        
        // 得到照片长宽
        String realPath = getAttachmentRoot() + "/" + photo.getOrgiUri();
        Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName("jpg");
        ImageReader reader = readers.next();
        File file = new File(realPath);
        try {
            ImageInputStream input = ImageIO.createImageInputStream(file);
            reader.setInput(input, true);
            int width = reader.getWidth(0);
            int height = reader.getHeight(0);
            map.put("width", width);
            map.put("height", height);
            input.close();
        }
        catch (Exception e) {
            logger.error("获取照片长宽", e);
        }
        
        List<PhotoMarkerDto> markers = PhotoMarkerDto.from(attachmentFinder.getPhotoMarkers(id));
        map.put("markers", markers);
        
        return "station/photo";
    }
    
    @RequestMapping("/stationRecord/detail.json")
    @ResponseBody
    public Object getStationRecordDetail(String id, String stationId) {
    	StationRecord stationRecordRecod;
    	if (StringUtils.isEmpty(id)) {
    		stationRecordRecod = stationFinder.getStationRecordByStationId(stationId);
    	}else{
    		stationRecordRecod = stationFinder.getStationRecordById(id);
    	}
    	
        if (stationRecordRecod == null) {
            return JsonUtils.failedMap("您查找的任务不存在！");
        }
        
        StationRecordDto dto = StationRecordDto.from(stationRecordRecod, entityManager);
		return JsonUtils.succeedMap(dto);
    }
    
    @RequestMapping("/stationRecord/save.json")
    @ResponseBody
    public Object saveStationRecord(StationRecordDto dto) {
        try {
        	StationRecord stationRecord = null;
            if (StringUtils.isNotEmpty(dto.getId())) {
            	stationRecord = entityManager.find(StationRecord.class, dto.getId());
            }
            if (stationRecord == null) {
            	return JsonUtils.failedMap("错误的参数！");
            }
            
            stationRecord = StationRecordDto.to(stationRecord, dto, entityManager);
            
            entityManager.persist(stationRecord);
            return getStationRecordDetail(stationRecord.getId(), null);
        }
        catch (Exception e) {
            logger.error(e, e);
            
            return JsonUtils.failedMap(e.getMessage());
        }
    }
}
